# 导入模块
import sys
# 窗口配置
from PyQt5.QtWidgets import *
# 图像相关
from PyQt5.QtGui import *
# QtCore相关
from PyQt5.QtCore import *
sys.path.append('../')
from ui.Ui_ConnectDialog import Ui_Dialog
from driver.bluetoothTest import BluetoothDataTransfer
from common.dataHandle import dataHandle
import threading

class MyDialog(QDialog):
    
    setMessageTextSignal = pyqtSignal(str)
    closeSignal = pyqtSignal()
    receiveDataSignal = pyqtSignal(bytes)
    
    def __init__(self, parent = None):
        super().__init__(parent)

        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        
        self.dataHandle = dataHandle()
        self.deviceList = [] # 设备列表
        self.BluetoothDataTransfer = None

        self.init_ui()

    def init_ui(self):
        self.scanBluetooth()
        # 连接蓝牙
        self.ui.connectButton.clicked.connect(self.connectBluetooth)
        # 返回
        self.ui.backButton.clicked.connect(self.close)
        # 设置消息标签文本
        self.setMessageTextSignal.connect(self.setMessageTextSlot)
        # 关闭页面
        self.closeSignal.connect(self.close)
        self.receiveDataSignal.connect(self.dataHandle.receiveDataVerifySlot)
        self.ui.refreshButton.clicked.connect(self.scanBluetooth)
    
    def scanBluetooth(self):
        self.ui.messageLabel.setText("设备搜索中...")
        # 扫描蓝牙
        threading.Thread(target = self.scanBluetoothThread, daemon = True).start()
        
    def scanBluetoothThread(self):
        self.deviceList = BluetoothDataTransfer.scan_devices()
        
        self.ui.deviceComboBox.clear()
        
        for device in self.deviceList:
            name = device[1]
            name = name.strip()
            if name != "":
                self.ui.deviceComboBox.addItem(name)
        
        self.ui.deviceComboBox.setCurrentIndex(0)
        self.ui.messageLabel.setText("扫描成功!")  
        
    def connectBluetooth(self):         
        self.ui.messageLabel.setText("正在连接....")
        
        name = self.ui.deviceComboBox.currentText()
        for device in self.deviceList:
            if name == device[1]:
                address = device[0]
            
        self.BluetoothDataTransfer = BluetoothDataTransfer(address, name)
        
        threading.Thread(target=self.connectBluetoothThread, daemon=True).start()
    
    def connectBluetoothThread(self):             
        flag = self.BluetoothDataTransfer.connect()
        if flag:
            self.setMessageTextSignal.emit("连接成功!")
            self.receiveDataSlot()
            self.closeSignal.emit()
        else:
            self.setMessageTextSignal.emit("连接失败!")
            
    def receiveDataSlot(self):
        threading.Thread(target=self.receiveBluetoothData, daemon = True).start()
    
    def receiveBluetoothData(self):
        while True:
            try:
                receiveData = self.BluetoothDataTransfer.receive_data()
                # print(receiveData)
                if receiveData:
                    # print(receiveData)
                    self.receiveDataSignal.emit(receiveData)
                else:
                    break
            except Exception as e:
                pass
            
    def sendData(self, data):
        threading.Thread(target=self.sendDataThread, args=(data,)).start()
    
    def sendDataThread(self, data):
        try:
            self.BluetoothDataTransfer.send_data(data)
        except Exception as e:
            pass

    # 设置消息标签文本
    def setMessageTextSlot(self, str):
        self.ui.messageLabel.setText(str)
    
    def closeSlot(self):
        self.close()
        
    def disconnnectBluetooth(self):
        try:
            self.BluetoothDataTransfer.disconnect()
        except Exception as e:
            pass
        
if __name__ == '__main__':
    # 创建应用程序
    app = QApplication(sys.argv)

    # 创建窗口
    w = MyDialog()

    # 显示窗口
    w.show()

    # 等待程序结束
    sys.exit(app.exec_())